package com.xiaolong.redis.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.xiaolong.redis.aspectj.CacheAspect;
import com.xiaolong.redis.aspectj.LockAspect;
import com.xiaolong.redis.handle.ExpireCacheHandler;
import com.xiaolong.redis.handle.NoExpirationCacheHandler;
import com.xiaolong.redis.handle.QueueLockHandler;
import com.xiaolong.redis.util.CacheUtil;
import jodd.util.StringUtil;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.TransportMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.StringUtils;

@AutoConfiguration
@EnableAspectJAutoProxy
@EnableConfigurationProperties(RedisProperties.class)
public class RedisTemplateAutoConfiguration {


    @Autowired
    private RedisProperties redisProperties;


    @Bean
    @ConditionalOnMissingBean
    public LettuceConnectionFactory redisConnectionFactory(@Autowired RedisProperties redisProperties) {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
        config.setHostName(redisProperties.getHost());
        config.setPort(redisProperties.getPort());
        if (StringUtils.hasText(redisProperties.getPassword())) {
            config.setPassword(redisProperties.getPassword());
        }
        return new LettuceConnectionFactory(config);
    }

    @Bean
    @ConditionalOnMissingBean
    public RedissonClient redissonClient() {
        Config config = new Config();
        config.setTransportMode(TransportMode.NIO);
        String address = String.format("redis://%s%s:%d",
                StringUtil.isBlank(redisProperties.getPassword()) ? "" : ":" + redisProperties.getPassword() + "@",
                redisProperties.getHost(), redisProperties.getPort());
        config.useSingleServer().setAddress(address);
        return Redisson.create(config);

    }

    @Bean
    @ConditionalOnMissingBean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(mapper, Object.class);

        // 设置key和value的序列化规则
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();
        CacheUtil.init(template);
        return template;
    }



    @Bean
    @ConditionalOnMissingBean
    public LockAspect lockAspect(){
        return new LockAspect();
    }

    @Bean
    @ConditionalOnMissingBean
    public QueueLockHandler queueLockHandler(){
        return new QueueLockHandler();
    }


    @Bean
    @ConditionalOnMissingBean
    public CacheAspect cacheAspect(@Autowired RedissonClient client){
        return new CacheAspect(client);
    }

    @Bean
    @ConditionalOnMissingBean
    public NoExpirationCacheHandler noExpirationCacheHandler(){
        return new NoExpirationCacheHandler();
    }

    @Bean
    @ConditionalOnMissingBean
    public ExpireCacheHandler expireCacheHandler(){
        return new ExpireCacheHandler();
    }

}
